package com.xkdx.guangguang.fragment.myinfomation;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.xkdx.caipiao.R;
import com.xkdx.guangguang.ManagerActivity;
import com.xkdx.guangguang.fragment.BaseFragment;
import com.xkdx.guangguang.fragment.brand.BrandInfoFragment;
import com.xkdx.guangguang.fragment.brand.branch.BranchFragment;
import com.xkdx.guangguang.fragment.home.homedetail.HomeDetailFragment;
import com.xkdx.guangguang.fragment.newsinfo.DiscountFragment;
import com.xkdx.guangguang.fragment.newsinfo.NewsFragment;
import com.xkdx.guangguang.fragment.shopinfo.ShopInfoFragment;
import com.xkdx.guangguang.fragment.user.UserSharePrefence1;
import com.xkdx.guangguang.module.network.AbsModule;
import com.xkdx.guangguang.module.statics.IConstants;
import com.xkdx.guangguang.shareclass.InfoManager;
import com.xkdx.guangguang.wiget.XListView;
import com.xkdx.guangguang.wiget.XListView.IXListViewListener;

public class InfoNotificationFragment extends BaseFragment implements
		OnClickListener {

	private View view_info;
	private Button back;
	private TextView tv_system, tv_self;

	private UserSharePrefence1 sp;
	private String userID;
	private String userToken;

	// ********
	// 个人信息
	// ********
	private XListView self_listView;
	public static boolean isself_LoadMore = false;
	private SeflAdapter self_adapter;
	private int self_info_PageIndex = 1;
	private int self_info_PageSize = 10;
	private List<InfoManager> info_self_list = new ArrayList<InfoManager>();
	private InfoSelfAction infoSelfAction;
	private InfoSelfModule infoselfModule;
	private InfoSelfPresistence infoselfPresenter;

	// ********
	// 系统消息
	// ********
	private XListView system_listView;
	public static boolean issystem_LoadMore = false;
	private SystemAdapter system_adapter;
	private int system_info_PageIndex = 1;
	private int system_info_PageSize = 10;
	private List<InfoManager> info_system_list = new ArrayList<InfoManager>();
	private InfoSystemAction infoSystemAction;
	private InfoSystemModule infoSytemModule;
	private InfoSystemPresistence infoSystemPresenter;

	private int num = 0;

	// ********
	// 删除操作
	// ********
	private DeleteInfoSelfAction deleteInfoSelfAction;
	private DeleteInfoSelfModule deleteInfoSelfModule;
	private DeleteInfoSelfPresistence deleteInfoSelfPresistence;
	private int deleteIndex = -1;
	private int pos = -1;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		sp = new UserSharePrefence1(getActivity(), IConstants.SP_USER_NEW);
		userID = sp.getId();
		userToken = sp.getLogintoken();
		// 清除消息提示
		IConstants.isHasPush = false;
		IConstants.isFromSelf = false;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		view_info = inflater.inflate(R.layout.info_notification, container,
				false);
		findView();
		setOnClick();
		ShowSystemLoading(false);
		return view_info;
	}

	@Override
	public void findView() {
		back = (Button) view_info.findViewById(R.id.info_back);
		tv_system = (TextView) view_info.findViewById(R.id.info_system);
		tv_self = (TextView) view_info.findViewById(R.id.info_self);
		tv_system.setBackgroundResource(R.drawable.info_bg_switch);
		tv_self.setBackgroundResource(0);

		// 系统消息listview
		system_listView = (XListView) view_info
				.findViewById(R.id.info_systemlist);
		system_listView.setPullLoadEnable(false);
		system_listView.setXListViewListener(new SecondXListViewListener());

		// 个人信息listview
		self_listView = (XListView) view_info.findViewById(R.id.info_selflist);
		self_listView.setPullLoadEnable(false);
		self_listView.setXListViewListener(new FirstXListViewListener());

	}

	@Override
	public void setOnClick() {
		back.setOnClickListener(this);
		tv_system.setOnClickListener(this);
		tv_self.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.info_system:
			tv_system.setBackgroundResource(R.drawable.info_bg_switch);
			tv_self.setBackgroundResource(0);
			system_listView.setVisibility(View.VISIBLE);
			self_listView.setVisibility(View.GONE);

			break;

		case R.id.info_self:
			if ("".equals(userToken)) {
				SelfUserLogin();
			} else {
				tv_self.setBackgroundResource(R.drawable.info_bg_switch);
				tv_system.setBackgroundResource(0);
				self_listView.setVisibility(View.VISIBLE);
				system_listView.setVisibility(View.GONE);

				if (num == 0) {
					ShowSelfLoading(false);
					num++;
				} else {
					setListAdapter(info_self_list);
				}
			}
			break;
		case R.id.info_back:
			getActivity().finish();
			break;
		}
	}

	private void ShowSelfLoading(boolean isFromRefresh) {
		if (!isFromRefresh) {
			if (dataLoadDialog != null && !(dataLoadDialog.isShowing())) {
				dataLoadDialog.show();
			}
		}

		userID = sp.getId();
		userToken = sp.getLogintoken();

		self_info_PageIndex = 1;
		infoSelfAction = new InfoSelfAction(userID, userToken, "2",
				self_info_PageIndex + "", self_info_PageSize + "");
		infoselfModule = new InfoSelfModule();
		infoselfPresenter = new InfoSelfPresistence(
				InfoNotificationFragment.this);
		((ManagerActivity) getActivity()).addCurrentTask(infoselfPresenter);
		infoselfPresenter.setActitons(infoSelfAction);
		infoselfPresenter.setModule(infoselfModule);
		infoselfPresenter.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dataLoadDialog) {
				if (infoselfPresenter != null) {
					infoselfPresenter.cancel(true);

				}
				getFragmentManager().popBackStack();
			}
		});

	}

	@Override
	public void showLoading() {
	}

	/**
	 * 删除请求结果
	 * 
	 * @param map
	 */
	public void showDeleteLoaded(HashMap<String, AbsModule> map) {

		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (map.containsKey("0")) {
			boolean isDel = false;
			isDel = ((DeleteInfoSelfModule) map.get("0")).isDelete;
			if (isDel) {
				Toast.makeText(getActivity(), "消息删除成功", Toast.LENGTH_SHORT).show();
				if (deleteIndex != -1) {
					info_self_list.remove(deleteIndex);
				}
				self_adapter.notifyDataSetChanged();
				deleteIndex = -1;
			} else {
				deleteIndex = -1;
				Toast.makeText(getActivity(), "消息删除失败", Toast.LENGTH_SHORT).show();
			}

		} else {
			deleteIndex = -1;
			showErrorTip(map);
		}
		onLoad();
	}

	@Override
	public void showLoaded(HashMap<String, AbsModule> map) {
		isself_LoadMore = false;
		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (map.containsKey("0")) {
			info_self_list.clear();
			info_self_list = ((InfoSelfModule) map.get("0")).infoSelfManagerList;

		} else {
			showErrorTip(map);
		}
		setListAdapter(info_self_list);
		onLoad();
	}

	private void onLoad() {
		self_listView.stopRefresh();
		self_listView.stopLoadMore();
		self_listView.setRefreshTime(getCurrentTime());
	}

	private void onFinishedLoad() {
		system_listView.stopRefresh();
		system_listView.stopLoadMore();
		system_listView.setRefreshTime(getCurrentTime());
	}

	public void showSystemLoaded(HashMap<String, AbsModule> map) {
		issystem_LoadMore = false;
		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}
		if (map.containsKey("0")) {

			info_system_list = ((InfoSystemModule) map.get("0")).infoSystemManagerList;

			// setFinishedListAdapter(info_system_list);

		} else {
			showErrorTip(map);
		}
		setFinishedListAdapter(info_system_list);
		onFinishedLoad();
	}

	private String getCurrentTime() {
		SimpleDateFormat format = new SimpleDateFormat("MM-dd hh:mm");
		Date date = new Date(System.currentTimeMillis());
		return format.format(date);
	}

	public void showOtherLoaded(HashMap<String, AbsModule> map) {
		isself_LoadMore = false;
		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}

		if (map.containsKey("0")) {

			for (InfoManager InfoManager : ((InfoSelfModule) map.get("0")).infoSelfManagerList) {
				info_self_list.add(InfoManager);
			}

			self_adapter.notifyDataSetChanged();
			if (((InfoSelfModule) map.get("0")).infoSelfManagerList.size() == self_info_PageSize) {
				self_listView.setPullLoadEnable(true);
			} else {
				self_listView.setPullLoadEnable(false);
			}

		} else {
			showErrorTip(map);
		}
		onLoad();
	}

	public void showOtherSystemLoaded(HashMap<String, AbsModule> map) {
		issystem_LoadMore = false;
		if (dataLoadDialog != null && dataLoadDialog.isShowing()) {
			dataLoadDialog.dismiss();
		}

		if (map.containsKey("0")) {

			for (InfoManager InfoManager : ((InfoSystemModule) map.get("0")).infoSystemManagerList) {
				info_system_list.add(InfoManager);
			}

			system_adapter.notifyDataSetChanged();
			if (((InfoSystemModule) map.get("0")).infoSystemManagerList.size() == system_info_PageSize) {
				system_listView.setPullLoadEnable(true);
			} else {
				system_listView.setPullLoadEnable(false);
			}

		} else {
			showErrorTip(map);
		}
		onFinishedLoad();
	}

	protected void setListAdapter(final List<InfoManager> orderList) {
		self_adapter = new SeflAdapter(getActivity(), orderList);
		self_listView.setAdapter(self_adapter);
		if (orderList.size() != 0 && orderList.size() % self_info_PageSize == 0) {
			self_listView.setPullLoadEnable(true);
		} else {
			self_listView.setPullLoadEnable(false);
		}

		self_listView
				.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {

					@Override
					public void onCreateContextMenu(ContextMenu menu, View v,
							ContextMenuInfo menuInfo) {
						menu.setHeaderTitle("将"
								+ info_self_list.get(pos).getTitle());
						menu.setHeaderIcon(android.R.drawable.ic_dialog_alert);
						menu.add(0, 0, 0, "从订制消息删除");
					}
				});

		self_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position != 0) {

					// InfoDetailFragment infoDetailFragment = new
					// InfoDetailFragment();
					// Bundle b = new Bundle();
					// b.putSerializable("info", orderList.get(position - 1));
					// infoDetailFragment.setArguments(b);
					//
					// getFragmentManager().beginTransaction()
					// .add(R.id.fragment, infoDetailFragment)
					// .addToBackStack(null)
					// .hide(InfoNotificationFragment.this).commit();
					// IConstants.isHasPush = true;
					// Intent intent = new Intent(getActivity(),
					// HomeActivity.class);
					// startActivity(intent);
					IConstants.objectType = orderList.get(position - 1)
							.getObjectType();
					IConstants.objectValue = orderList.get(position - 1)
							.getObjectID();

					InfoConvert();
				}
			}
		});

		self_listView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				pos = position - 1;
				return false;
			}
		});
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		final AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
				.getMenuInfo();

		final int id = (int) info.id;
		deleteIndex = id;

		if (-1 == id) {
			super.onContextItemSelected(item);
		}

		switch (item.getItemId()) {
		case 0:
			showDelete(id);
			break;
		}
		return super.onContextItemSelected(item);
	}

	// private void showDialog(int id) {
	// new AlertDialog.Builder(this).setTitle("我的提示").setMessage("确定要删除吗？")
	// .setPositiveButton("确定", new DialogInterface.OnClickListener() {
	// @Override
	// public void onClick(DialogInterface dialog, int which) {
	// mData.remove(position);
	// setListAdapter(adapter);
	// }
	// }).show();
	// }

	private void showDelete(int id) {
		if (dataLoadDialog != null && !dataLoadDialog.isShowing()) {
			dataLoadDialog.show();
		}
		userID = sp.getId();
		userToken = sp.getLogintoken();

		deleteInfoSelfAction = new DeleteInfoSelfAction(userID, userToken, "2",
				info_self_list.get(id).getId());

		deleteInfoSelfModule = new DeleteInfoSelfModule();
		deleteInfoSelfPresistence = new DeleteInfoSelfPresistence(
				InfoNotificationFragment.this);
		((ManagerActivity) getActivity())
				.addCurrentTask(deleteInfoSelfPresistence);
		deleteInfoSelfPresistence.setActitons(deleteInfoSelfAction);
		deleteInfoSelfPresistence.setModule(deleteInfoSelfModule);
		deleteInfoSelfPresistence.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dataLoadDialog) {
				if (infoselfPresenter != null) {
					infoselfPresenter.cancel(true);

				}
				getFragmentManager().popBackStack();
			}
		});
	}

	protected void setFinishedListAdapter(final List<InfoManager> orderList) {
		system_adapter = new SystemAdapter(getActivity(), orderList);
		system_listView.setAdapter(system_adapter);

		if (orderList.size() != 0
				&& orderList.size() % system_info_PageSize == 0) {
			system_listView.setPullLoadEnable(true);
		} else {
			system_listView.setPullLoadEnable(false);
		}

		system_listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				if (position != 0) {
					// InfoDetailFragment infoDetailFragment = new
					// InfoDetailFragment();
					// Bundle b = new Bundle();
					// b.putSerializable("info", orderList.get(position - 1));
					// infoDetailFragment.setArguments(b);
					//
					// getFragmentManager().beginTransaction()
					// .add(R.id.fragment, infoDetailFragment)
					// .addToBackStack(null)
					// .hide(InfoNotificationFragment.this).commit();

					// Intent intent = new Intent(getActivity(),
					// HomeActivity.class);
					// startActivity(intent);
					// IConstants.isHasPush = true;
					IConstants.objectType = orderList.get(position - 1)
							.getObjectType();
					IConstants.objectValue = orderList.get(position - 1)
							.getObjectID();

					InfoConvert();

				}
			}
		});
	}

	protected void InfoConvert() {
		IConstants.isHasSelfPush = false;
		int type = Integer.valueOf(IConstants.objectType);
		switch (type) {
		case 1:

			break;
		case 2:
			// IConstants.download(getActivity(),
			// "dl.guangguang.net.cn/GuangGuang.apk");
			break;
		case 3:
			HomeDetailFragment detail = new HomeDetailFragment();
			Bundle b3 = new Bundle();
			b3.putString("infoID", IConstants.objectValue);
			detail.setArguments(b3);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, detail).addToBackStack(null)
					.commit();
			break;
		case 4:
			ShopInfoFragment info = new ShopInfoFragment();
			Bundle b4 = new Bundle();
			b4.putString("shopID", IConstants.objectValue);
			info.setArguments(b4);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, info).addToBackStack(null).commit();
			break;
		case 5:
			BranchFragment branchFragment = new BranchFragment();
			Bundle b5 = new Bundle();
			b5.putString("shopID", IConstants.objectValue);
			branchFragment.setArguments(b5);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, branchFragment)
					.addToBackStack(null).commit();
			break;
		case 6:
			BrandInfoFragment brandInfo = new BrandInfoFragment();
			Bundle b6 = new Bundle();
			b6.putString("brandID", IConstants.objectValue);
			brandInfo.setArguments(b6);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, brandInfo).addToBackStack(null)
					.commit();
			break;
		case 7:
			NewsFragment newsFragment = new NewsFragment();
			Bundle b7 = new Bundle();
			b7.putString("infoID", IConstants.objectValue);
			newsFragment.setArguments(b7);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, newsFragment).addToBackStack(null)
					.commit();

			break;
		case 8:
			DiscountFragment discountInfo = new DiscountFragment();
			Bundle b8 = new Bundle();
			b8.putString("infoID", IConstants.objectValue);
			discountInfo.setArguments(b8);
			getFragmentManager().beginTransaction()
					.replace(R.id.fragment, discountInfo).addToBackStack(null)
					.commit();

			break;
		default:

			break;
		}
		IConstants.objectType = "1";
		IConstants.objectValue = "1";

	}

	/**
	 * 第一次或刷新执行系统消息加载过程
	 */
	private void ShowSystemLoading(boolean isfromRefresh) {
		if (!isfromRefresh) {
			if (dataLoadDialog != null && !(dataLoadDialog.isShowing())) {
				dataLoadDialog.show();
			}
		}
		userID = sp.getId();
		userToken = sp.getLogintoken();
		system_info_PageIndex = 1;
		infoSystemAction = new InfoSystemAction("2",
				system_info_PageIndex + "", system_info_PageSize + "");
		infoSytemModule = new InfoSystemModule();
		infoSystemPresenter = new InfoSystemPresistence(this);
		((ManagerActivity) getActivity()).addCurrentTask(infoSystemPresenter);
		infoSystemPresenter.setActitons(infoSystemAction);
		infoSystemPresenter.setModule(infoSytemModule);
		infoSystemPresenter.execute();
		dataLoadDialog.setOnCancelListener(new OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dataLoadDialog) {
				if (infoSystemPresenter != null) {
					infoSystemPresenter.cancel(true);

				}
				getFragmentManager().popBackStack();
			}
		});
	}

	public class SeflAdapter extends BaseAdapter {

		private List<InfoManager> list;

		public SeflAdapter(Context context, List<InfoManager> list) {
			this.list = list;
		}

		@Override
		public int getCount() {

			return list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			ViewHolder viewHolder;
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.info_item, null);
				viewHolder = new ViewHolder();
				viewHolder.tv_info_summary = (TextView) convertView
						.findViewById(R.id.tv_info_summary);
				viewHolder.tv_info_time = (TextView) convertView
						.findViewById(R.id.tv_info_time);
				viewHolder.tv_info_detail = (TextView) convertView
						.findViewById(R.id.tv_info_detail);

				convertView.setTag(viewHolder);
			} else {
				viewHolder = (ViewHolder) convertView.getTag();
			}

			viewHolder.tv_info_summary.setText(list.get(position).getTitle());
			viewHolder.tv_info_time.setText(list.get(position).getSendTime());
			viewHolder.tv_info_detail.setText(list.get(position).getMessage());

			return convertView;
		}
	}

	private class ViewHolder {

		TextView tv_info_summary, tv_info_time, tv_info_detail;
	}

	public class SystemAdapter extends BaseAdapter {

		private List<InfoManager> list;

		public SystemAdapter(Context context, List<InfoManager> list) {
			this.list = list;
		}

		@Override
		public int getCount() {

			return list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder2 viewHolder2;
			if (convertView == null) {
				convertView = LayoutInflater.from(getActivity()).inflate(
						R.layout.info_item, null);
				viewHolder2 = new ViewHolder2();
				viewHolder2.tv_info_summary = (TextView) convertView
						.findViewById(R.id.tv_info_summary);
				viewHolder2.tv_info_time = (TextView) convertView
						.findViewById(R.id.tv_info_time);
				viewHolder2.tv_info_detail = (TextView) convertView
						.findViewById(R.id.tv_info_detail);

				convertView.setTag(viewHolder2);
			} else {
				viewHolder2 = (ViewHolder2) convertView.getTag();
			}

			viewHolder2.tv_info_summary.setText(list.get(position).getTitle());
			 viewHolder2.tv_info_time.setText(list.get(position).getSendTime());
			viewHolder2.tv_info_detail.setText(list.get(position).getMessage());

			return convertView;
		}
	}

	private class ViewHolder2 {
		TextView tv_info_summary, tv_info_time, tv_info_detail;
	}

	public class FirstXListViewListener implements IXListViewListener {

		public FirstXListViewListener() {

		}

		@Override
		public void onRefresh() {
			ShowSelfLoading(false);
		}

		@Override
		public void onLoadMore() {
			if (!isself_LoadMore) {
				isself_LoadMore = true;
				self_info_PageIndex++;

				// infoSelfAction = new InfoSelfAction("1290",
				// "855de6e23b8b7489e95d638d8c939be7", "2",
				// self_info_PageIndex + "", self_info_PageSize + "");
				userID = sp.getId();
				userToken = sp.getLogintoken();

				infoSelfAction = new InfoSelfAction(userID, userToken, "2",
						self_info_PageIndex + "", self_info_PageSize + "");
				// infoselfModule = new InfoSelfModule();
				infoselfPresenter = new InfoSelfPresistence(
						InfoNotificationFragment.this);
				((ManagerActivity) getActivity())
						.addCurrentTask(infoselfPresenter);
				infoselfPresenter.setActitons(infoSelfAction);
				infoselfPresenter.setModule(infoselfModule);
				infoselfPresenter.execute();

			}
		}
	}

	public class SecondXListViewListener implements IXListViewListener {

		@Override
		public void onRefresh() {
			ShowSystemLoading(false);
		}

		@Override
		public void onLoadMore() {
			if (!issystem_LoadMore) {
				issystem_LoadMore = true;
				system_info_PageIndex++;
				infoSystemAction = new InfoSystemAction("2",
						system_info_PageIndex + "", system_info_PageSize + "");
				infoSytemModule = new InfoSystemModule();
				infoSystemPresenter = new InfoSystemPresistence(
						InfoNotificationFragment.this);
				((ManagerActivity) getActivity())
						.addCurrentTask(infoSystemPresenter);
				infoSystemPresenter.setActitons(infoSystemAction);
				infoSystemPresenter.setModule(infoSytemModule);
				infoSystemPresenter.execute();

			}
		}

	}

	@Override
	public void showClick(HashMap<String, AbsModule> map) {
	}

	@Override
	public void showLoadMore(HashMap<String, AbsModule> map) {
	}

}
